<?php

namespace App\Tools;

class Instagraph
{
  public $_image = NULL;
  public $_output = NULL;
  public $_prefix = 'IMG';
  private $_width = NULL;
  private $_height = NULL;
  private $_tmp = NULL;

  public static function factory($image, $output)
  {
    return new Instagraph($image, $output);
  }

  public function __construct($image, $output)
  {
    if (file_exists($image)) {
      $this->_image = $image;
      list($this->_width, $this->_height) = getimagesize($image);
      $this->_output = $output;
    } else {
      throw new Exception('File not found. Aborting.');
    }
  }

  public function tempfile()
  {
    # copy original file and assign temporary name
    $this->_tmp = $this->_prefix . rand();
    copy($this->_image, $this->_tmp);
  }

  public function output()
  {
    # rename working temporary file to output filename
    rename($this->_tmp, $this->_output);
  }

  public function execute($command)
  {
    # remove newlines and convert single quotes to double to prevent errors
    $command = str_replace(array("\n", "'"), array('', '"'), $command);
    $command = escapeshellcmd($command);
    # execute convert program
    exec('/usr/local/imagemagick/bin/' . $command);
  }

  public function withText($position, $fontSize, $fonts)
  {
    $this->tempfile();
    $command = "convert {$this->_tmp} -gravity {$position} -pointsize {$fontSize} -stroke '#000C' -strokewidth {$fontSize} -stroke  none   -fill white    -annotate 0 '{$fonts}' $this->_tmp";
    $this->execute($command);
    $this->output();
  }
}
